'''
Created on Apr 28, 2010

@author: william
'''

# This package requires the installation of the "netifaces" python
# module, which can be found at: 
# http://pypi.python.org/pypi/netifaces/0.4

import platform
import os
import socket
import netifaces

# Gets the OS information to be used by the client.
def os():
    os = {'Operating System':platform.system(),
          'Release':platform.release(), # Gets the Linux Kernel or Windows version.
          'CPU':platform.machine()} # Retrieves the CPU type.
 
    # Retrieves Linux Distribution if host is Linux
    if platform.system() == 'Linux':
        distro = {}
        distro['Distribution'] = platform.dist()[0]
        distro['Version'] = platform.dist()[1]
        os['Distrubution'] = distro
    return os

# Gets network information from the client.
def network():
    network = {'Hostname':socket.getfqdn(), # Socket.getfqdn gets us the FQDN of the machine.
               'Interfaces':netifaces.interfaces(),
               'IP Address':ip('addr'),
               'MAC Address':ip('mac'),
               'Subnet':ip('netmask'),
               'Broadcast':ip('broadcast')}
    return network

# Valid arguments for this module are "addr", "netmask", "mac", and
# "broadcast". Returns the host computer's IP information.
def ip(addr):
    # Retrieves the interfaces from the host machine.
    interface = netifaces.interfaces()
    ip = {}
    
    # If specifying the MAC address, we need to address a different part
    # of the output of "netifaces.ifaddresses". So we use an if statement
    # to determine which method to use.
    if addr == 'mac':
        for line in interface:
            try: # This tries each interface and returns the MAC address
                ip[line] = netifaces.ifaddresses(line)[netifaces.AF_LINK][0]['addr']
            except: # If a MAC Address is not found, it handles the exception.
                print 'No MAC Address found for interface:', line
                ip[line] = '' # If nothing's found, it sets it to null.
    else:    
        # Gets the IP Address from each interface.
        for line in interface:
            try:
                ip[line] = netifaces.ifaddresses(line)[netifaces.AF_INET][0][addr]
            except: # If no information is found, handle the exception.
                print 'No', addr, 'information found for interface:', line
                ip[line] = '' # If there's no IP info, it sets it to null.
    return ip
     

print network()